package com.ymt.fmd.util;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import org.apache.commons.beanutils.PropertyUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.fmd.util.DateUtil;

/**
 * 

 * @ClassName: DhxUtil

 * @Description: Dhtmlx数据处理相关类

 * @author Johnny

 * @date 2015-12-24 下午2:59:53
 */
public class DhxUtil {

	/**
	 *  Dhx grid empty json
	 */
	public static final String EMPTY_GRIDJSON = "{\"rows\":[], \"total_count\":0}";
	/**
	 * Dhx grid rows
	 */
	public static final String ROWS = "rows";
	/**
	 * Dhx grid data
	 */
	public static final String DATA = "data";
	/**
	 * Dhx grid id
	 */
	public static final String ID = "id";
	/**
	 * Dhx grid position
	 */
	public static final String POS = "pos";
	/**
	 * Dhx grid total count
	 */
	public static final String TOTAL_COUNT = "total_count";
	/**
	 * 日期格式  英文
	 */
	public static final String GRID_DATEFORMAT_EN = "%M/%D/%Y";
	/**
	 * 日期格式 中文
	 */
	public static final String GRID_DATEFORMAT_ZH = "%Y-%M-%D";
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(DhxUtil.class.getName());
	
	/**
	 * translate db result to grid json.
	 * @param list
	 * @param cols
	 * @param fromRow
	 * @param total
	 * @param timezoneOffset
	 * @param lang
	 * @return
	 */
	public static String toGridJsonStr(List<Map<String, ?>> list, String[] cols, int fromRow, int total, int timezoneOffset, String lang) {
		if (list==null) {
			return null;
		}
		if (list.size()==0) {
			return EMPTY_GRIDJSON;
		}
		JSONObject rtn = new JSONObject();
		JSONArray rows = new JSONArray();
		for (int i=0; i<list.size(); i++) {
			logger.finest("parsing map: "+list.get(i));
			JSONObject row = new JSONObject();
			JSONArray data = new JSONArray();
			data.add(fromRow + i);	//ROW NUMBER
			for (String col : cols) {
				data.add(formatValue(list.get(i).get(col.toUpperCase()), DateUtil.getSSFormatByLang(lang), lang, timezoneOffset));
			}
			//row.put(ID, fromRow + i -1);
			row.put(ID, fromRow + i);
			row.put(DATA, data);
			rows.add(row);
		}
		rtn.put(ROWS, rows);
		rtn.put(TOTAL_COUNT, total);
		rtn.put(POS, fromRow -1);
		return rtn.toString();
	}
	
	/**
	 * translate db result to grid json.
	 * @param list
	 * @param cols
	 * @param fromRow
	 * @param total
	 * @param timezoneOffset
	 * @param lang
	 * @return
	 */
	public static String toGridJsonBtStr(List<Map<String, ?>> list, String[] cols, int fromRow, int total, int timezoneOffset, String lang) {
		if (list==null) {
			return null;
		}
		JSONObject rtn = new JSONObject();
		JSONArray rows = new JSONArray();
		if (list.size()>0) {
			for (int i=0; i<list.size(); i++) {
				logger.finest("parsing map: "+list.get(i));
				JSONObject row = (JSONObject)JSONObject.toJSON(list.get(i));
				for (Map.Entry<String, Object> en : (Set<Map.Entry<String, Object>>)row.entrySet()) {
					if (en.getValue() instanceof Date) {
						en.setValue(formatValue(en.getValue(), DateUtil.getSSFormatByLang(lang), lang, timezoneOffset));
					}
				}
				row.put("NO_", fromRow+i);
				rows.add(row);
			}
		}
		rtn.put("rows", rows);
		rtn.put("total", total);
		return rtn.toString();
	}
	
	/**
	 * translate db result to grid json.
	 * @param list
	 * @param cols
	 * @param fromRow
	 * @param total
	 * @return
	 */
	public static String toGridJsonStrNoZone(List<Map<String, ?>> list, String[] cols, int fromRow, int total) {
		if (list==null) {
			return null;
		}
		if (list.size()==0) {
			return EMPTY_GRIDJSON;
		}
		JSONObject rtn = new JSONObject();
		JSONArray rows = new JSONArray();
		for (int i=0; i<list.size(); i++) {
			logger.finest("parsing map: "+list.get(i));
			JSONObject row = new JSONObject();
			JSONArray data = new JSONArray();
			data.add(fromRow + i + 1);	//ROW NUMBER
			for (String col : cols) {
				data.add(formatGridData(list.get(i).get(col)));
			}
			//row.put(ID, fromRow + i -1);
			row.put(ID, fromRow + i + 1);
			row.put(DATA, data);
			rows.add(row);
		}
		rtn.put(ROWS, rows);
		rtn.put(TOTAL_COUNT, total);
		rtn.put(POS, fromRow);
		return rtn.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static JSONObject toJsonWithDate(Object obj, String lang, int timezoneOffset) {
		JSONObject rtn;
		if (obj instanceof JSONObject) {
			rtn = (JSONObject) obj;
		} else {
			rtn = (JSONObject) JSONObject.toJSON(obj);
		}
		try {
			for (Object keyo : rtn.keySet()) {
				String key = (String) keyo;
				Object val = PropertyUtils.getProperty(obj, key);
				if(val instanceof Date) {
					rtn.put(key, DateUtil.formatDate((Date) val, DateUtil.getSSFormatByLang(lang), timezoneOffset));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return rtn;
	}
	
	public static <T> JSONArray toJsonWithDate(List<T> list, String lang, int timezoneOffset) {
		JSONArray ja = new JSONArray();
		if (list != null && list.size()>0) {
			for (int i=0; i<list.size(); i++) {
				ja.add(toJsonWithDate(list.get(i), lang, timezoneOffset));
			}
		}
		return ja;
	}
	
	/**
	 * format value by format predefined in ts_tablecolumnmeta.
	 * @param f
	 * @param val
	 * @return
	 */
	public static String formatValue(Object val, String f, String lang, int timezoneoffset) {
		if (val==null) {
			return null;
		}
		if (val instanceof java.math.BigDecimal) {
			return val.toString();
		} else if (val instanceof java.sql.Timestamp) {
			Date d = new Date(((java.sql.Timestamp) val).getTime());
			if (f != null && f.length()>0) {
				return DateUtil.formatDate(d, f, timezoneoffset);
			}
			return DateUtil.formatDate(d, DateUtil.getSSFormatByLang(lang), timezoneoffset);
		} else {
			return val.toString();
		}
	}
	
	public static String formatGridData(Object val) {
		if (val==null) {
			return null;
		}
		if (val instanceof java.math.BigDecimal) {
			return val.toString();
		} else if (val instanceof java.sql.Timestamp) {
			Date d = new Date(((java.sql.Timestamp) val).getTime());
			return DateUtil.formatDate(d, DateUtil.DATEFORMATSS_ZH,0);
		} else {
			return val.toString();
		}
	}
	
	/**
	 * parse order by columns to order by clause.
	 * @param ordercolumns
	 * @return
	 */
	public static String parseGridOrderBy(String ordercolumns) {
		if (ordercolumns==null || ordercolumns.trim().length()==0) {
			return "";
		}
		JSONArray ocs = JSONArray.parseArray(ordercolumns);
		StringBuilder sb = new StringBuilder(" ORDER BY");
		for (int i=0; i<ocs.size(); i++) {
			JSONObject oc = ocs.getJSONObject(i);
			String key = (String) oc.keySet().iterator().next();
			sb.append(i > 0 ? "," : " ").append(key).append(" ").append(oc.getString(key));
		}
		logger.finer("parseGridOrderBy translated "+ordercolumns+" to "+sb);
		return sb.toString();
	}
	
}
